import yaml
from marketplace.models import App,AppConfig
from webapp.serializer import HostListSerializer
from AnsibleGUI.settings import ANSIBLE_ROOT
from common.AnsibleExec import AnsibleExec
import json

class PlaybookGen():
    def __init__(self,AppId):
        self.AppId = AppId
        self.AppName = App.objects.get(id=self.AppId).name
        self.playbookpath = ANSIBLE_ROOT + self.AppName + '.yaml'
        self.groupvars = json.loads(self.__get_group_vars())
        self.hostlist = self.__get_host_list()

    def __get_host_list(self):
        host_list = []
        groups = App.objects.get(id=self.AppId).group.all()
        for group in groups:
            hosts_in_group = group.host_set.all()
            for host in hosts_in_group:
                if (HostListSerializer(host).data.items()) not in host_list:
                    host_list.append(HostListSerializer(host).data)
        return host_list

    def __get_group_vars(self):
        config = AppConfig.objects.get(app=self.AppId,active=True)
        return config.text

    def yaml_generate(self):
        ansible_yaml = []
        AppYaml = {}
        AppYaml['hosts'] = 'group'
        AppYaml['name'] = self.AppName
        AppYaml['tasks'] = []
        include = {}
        include['include_role'] = {}
        include['include_role']['name'] = self.AppName
        AppYaml['tasks'].append(include)
        ansible_yaml.append(AppYaml)
        data = yaml.dump(ansible_yaml)
        return data

    def RunPlaybook(self):
        with open(self.playbookpath, "w") as yaml_file:
            yaml_file.write(self.yaml_generate())
        resource = {"group":{"hosts":
                     self.hostlist,
                    "groupvars": self.groupvars
                             }}
        runner = AnsibleExec(resource)
        return runner.run_playbook(playbookpath=self.playbookpath)
